var app = getApp();

Page({
  data: {},
  onShow,
  onLoad,
  loadInit,
  scanCode,
  scanCodeParse, //参数解析
  getUserHand, //获取用户绑定的所有手环
  addUserEquipment, //绑定手环
})

function onShow() {
  var that = this;
  if (app.userInfo.userId) that.getUserHand();
}

function onLoad(options) {
  const that = this;
  that.setData({
    options,
  })
  app.xlogin.getUser(function(res) {
    that.loadInit();
  })
}

function loadInit() {
  const that = this;
  const options = that.data.options;
  //扫器械的二维码
  // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
  var result = decodeURIComponent(options.q);
  if (!result || result == 'undefined') return;
  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;
  that.scanCodeParse(result);
}

function scanCode() {
  var that = this;
  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;
  wx.scanCode({
    success: function(res) {
      var result = res.result;
      that.scanCodeParse(result);
    }
  });
}

function scanCodeParse(result) {
  const that = this;
  // 手环二维码
  // result = '12M30M1C67C451FBM7C';
  // 魔贴二维码
  // result = 'https://www.whochange.com/w?p=12M30M0E0E0E0E0E0EM0';
  if (!result || result == 'undefined') return;
  var codeParse = app.plugin.codeParse(result);
  console.log(codeParse)
  if (codeParse && codeParse.band) {
    console.log('这是手环的码')
    that.addUserEquipment(result);
    return false;
  } else if (codeParse) {
    console.log('这是魔贴的码')
    // 当前二维码为魔贴二维码反馈
    wx.navigateTo({
      url: app.xhx_route.fitDetail,
    })
    return true;
  } else {
    // 当前二维码为外部二维码反馈
    return false;
  }
}

function getUserHand() {
  app.middleware.requestAjax({
    serAddr: app.serAddrs.getUserEquipment,
    data: {
      type: 1
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    cancelToast: true,
    success: function(res) {
      try {
        var jsonHandles = [];
        for (var i = 0; i < res.data.userEquipmentList.length; i++) {
          // res.data.userEquipmentList[i].equipmentId = parseInt(res.data.userEquipmentList[i].equipmentId, 16);
          jsonHandles.push(res.data.userEquipmentList[i].equipmentId);
        }
        app.plugin.setHand(JSON.stringify(jsonHandles));
      } catch (e) {

      }
    }
  })
}

function addUserEquipment(result) {
  const that = this;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.addUserEquipment,
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      equipmentId: MtQRcodeParse(result).deviceId
    },
    success: function(res) {
      console.log('添加设备', res);
      app.middleware.showToast('手环设备绑定成功');
      that.onShow();
    },
    fail: function(res) {
      app.middleware.showToast('手环设备绑定失败');
    }
  })
}

// 二维码字段处理
function MtQRcodeParse(value) {
  var that = this;
  var link = value.split('=');
  var arr = [];
  if (!link[0]) return false;

  if (link.length > 1) {
    arr = link[1];
  } else {
    arr = link[0];
  }
  arr = arr.split('M');
  if (arr.length < 4) return false;
  var newArray = {
    'company_hardware': arr[0],
    'address': str_pad(arr[1]),
    'deviceId': arr[2],
    'moduleType': parseInt(arr[3], 16),
  }
  // 定制版唯一
  if (arr[4]) {
    newArray.onlyNo = arr[4];
  }
  return newArray;
}

function str_pad(hex) {
  var zero = '00000000';
  var tmp = 8 - hex.length;
  return zero.substr(0, tmp) + hex;
}